"""
翻页依赖于上一页的参数  如果某个之母的页数不对
删除该字母的所有html网页 重新下载
"""
import configparser
import io
import os
import sys
import time
import traceback
import warnings

import pymysql
from PIL import Image
from xjlibrary.mrequest.baserequest import BaseRequest
from xjlibrary.mysqlmoudel.simple.mysqlclient import SelctSqlFromDB, ExeSqlToDB, MySqlDbConnect
from xjlibrary.tools.BaseFile import BaseFile, SingleWriteFile
from xjlibrary.tools.BaseUrl import BaseUrl

baseurl = "http://10.38.48.163/tingbook/"
HEADERS = {
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
    "Accept-Encoding": "gzip, deflate",
    "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
    "Host": "10.38.48.163",
    "Proxy-Connection": "keep-alive",
    "Upgrade-Insecure-Requests": "1",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.62 Safari/537.36"
}
ListSql = []
curPath = BaseFile.get_path_absolute(__file__)
TopPath = BaseFile.get_top_path(curPath, -2)
sPath = BaseFile.getNewPath(TopPath, "download", "tianfang", "download", "cover")

proxyss = {
    "http": "192.168.30.176:8033",
    "https": "192.168.30.176:8033",
}


def requesthome(url):
    BoolResult, errString, r = BaseRequest(url, mark="", endstring="", headers=HEADERS, proxies=proxyss, timeout=45)
    if not BoolResult:
        print("请检查失败原因:" + errString)
        sys.exit(-1)
    return r

# 数据库链接
def MajorDbConnect():
    return MySqlDbConnect(curPath, "db.ini")



def SelectFromDB():
    sql = "select `imageurl` from `chapter` where `cover_stat`=0"
    conn = MajorDbConnect()
    cur = conn.cursor()
    rows = SelctSqlFromDB(sql, conn)
    return rows


def UpdateSql(sql):
    conn = MajorDbConnect()
    ExeSqlToDB(sql, conn, errExit=True)


def savefile(r, filePath):
    SingleWriteFile(r.text, filePath)

def Img2Jpg(buf, dstFile):
    print('Img2Jpg %s ...' % dstFile)

    exMsg = ''
    try:
        srcImg = Image.open(io.BytesIO(buf))
        dstImg = srcImg.resize((108, 150), Image.ANTIALIAS).convert('RGB')
        dstImg.save(dstFile, 'JPEG')
    except:
        exMsg = '* %s' % traceback.format_exc()
        print(exMsg)
    if exMsg:
        return False

    return True

def start():
    for row in SelectFromDB():
        url = baseurl + row[0]
        if not os.path.exists(sPath):
            os.makedirs(sPath)
        listurl = BaseUrl.urlPath2List(url)[-2:]
        filename = "_".join(listurl).replace("_picture", "").replace(".gif",".jpg")
        filePath = os.path.join(sPath, filename)
        if os.path.exists(filePath):
            print("文件存在" + filePath)
            sql = "update `chapter` set `cover_stat`=1 where `imageurl`='{}'".format(row[0])
            UpdateSql(sql)
            continue
        r = requesthome(url)
        Img2Jpg(r.content, filePath)
        sql = "update `chapter` set `cover_stat`=1 where `imageurl`='{}'".format(row[0])
        UpdateSql(sql)

def init():
    sql = "update `chapter` set `cover_stat`=0"
    UpdateSql(sql)

if __name__ == "__main__":
    init()
    start()